﻿using Max.PH4_2102A.Shopping.Domain;
using Max.PH4_2102A.Shopping.DTO;
using Max.PH4_2102A.Shopping.IRespository;
using Max.PH4_2102A.Shopping.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH4_2102A.Shopping.Service
{
    /// <summary>
    /// SPU服务实现（产品的服务实现)
    /// </summary>
    public class SPUService : ISPUService
    {

        ISPURespository _spuRespository;
        ISKURespository _skuRespository;
        ISPUSpecRespository _spuSpecRespository;
        ISKUImageRespository _skuImageRespository;
        IUnitOfWork _unitOfWork;

        public SPUService(ISPURespository spuRespository, ISKURespository skuRespository, ISPUSpecRespository spuSpecRespository, ISKUImageRespository skuImageRespository, IUnitOfWork unitOfWork)
        {
            _spuRespository = spuRespository;
            _skuRespository = skuRespository;
            _spuSpecRespository = spuSpecRespository;
            _skuImageRespository = skuImageRespository;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 获取SKU列表
        /// </summary>
        /// <returns></returns>
        public IQueryable<SKUModel> GetSKUList()
        {
            var list =  _skuRespository.GetAll();
            return list;
        }

        /*
         * 这个方法是添加某款产品，它包括：
         * SPU信息、SKU信息、SPU的规格信息、SKU的图片信息
         * 
         * **/
        public int AddProduct(ProductInputDto dto)
        {
            int result = 0;
            //事务的三步骤：开启事务、提交事务、回滚事务
            using (var tran = _unitOfWork.GetDbContext().Database.BeginTransaction())  //开启事务
            {
                try
                {
                    var _spuId = Guid.NewGuid();
                    //1、SPU信息
                    var spu = new Domain.SPUModel()
                    {
                        BrandId = dto.BrandId,
                        CategoryId = dto.CategoryId,
                        Id = _spuId,
                        Name = dto.Name,
                        Description = dto.Description
                    };

                    //2、SPU规格信息
                    var specs = new List<SPUSpecModel>();
                    dto.Specs.ForEach(x => {
                        specs.Add(new SPUSpecModel
                        {
                            Name = x.Name,
                            SPUId = spu.Id,
                            Value = x.Value
                        });
                    });

                    //3、SKU和SKU图片信息
                    var skus = new List<SKUModel>();
                    var skuImages = new List<SKUImageModel>();
                    dto.Skus.ForEach(x =>
                    {
                        var _skuId = Guid.NewGuid();
                        skus.Add(new SKUModel()
                        {
                            Cover = x.Cover,
                            Id = _skuId,
                            InPrice = x.InPrice,
                            LockStock = x.LockStock,
                            MarketPrice = x.MarketPrice,
                            SalePrice = x.SalePrice,
                            SourceStock = x.SourceStock,
                            Spec = x.Spec,
                            SPUId = spu.Id,
                            ValidStock = x.ValidStock
                        });

                        //一个SKU对应多个图片。现在将每个图片拼接一个model对象，并放到skuImages这个集合对象中
                        x.Images.ForEach(m =>
                        {
                            skuImages.Add(new SKUImageModel()
                            {
                                Path = m,
                                SKUId = _skuId
                            });
                        });
                    });

                    _spuRespository.Insert(spu);
                    _skuRespository.Insert(skus);
                    _skuImageRespository.Insert(skuImages);
                    _spuSpecRespository.Insert(specs);

                    _unitOfWork.SaveChanges();

                    tran.Commit(); //提交事务
                    result = 1;
                }
                catch (Exception)
                {
                    tran.Rollback(); //回滚事务
                    result = -1;
                    throw;
                }
                return result;
            }
        }

        /// <summary>
        /// 单个商品的上下架操作
        /// </summary>
        /// <param name="id">要修改的数据的主键id</param>
        public void UpdateProductState(string id)
        {
            //在所有的数据中，查找那条要修改的数据
            var m = _skuRespository.GetAll().Where(x => x.Id.ToString().Equals(id)).FirstOrDefault();

            if (m == null)
            {
                m.State = !m.State;
                _skuRespository.Update(m);
            }
        }

        /// <summary>
        /// 批量操作
        /// </summary>
        public void UpdateProductState(List<string> ids,bool value)
        {
            //根据id的集合，把符合条件的数据找出来
            var list = _skuRespository.GetAll().Where(x => ids.ToArray().Contains(x.Id.ToString()) && x.State == !value);
            list.ToList().ForEach(x =>
            {
                x.State = value;
                _skuRespository.Update(x);
            });



            foreach (string id in ids)
            {
                var m = _skuRespository.GetAll().Where(x => x.Id.ToString().Equals(id) && x.State == !value).FirstOrDefault();

                if (m == null)
                {
                    m.State = value;
                    _skuRespository.Update(m);
                }
            }
        }
    }
}
